//
//  HMOAuthViewController.swift
//  WeiBoXR
//
//  Created by acer on 16/9/21.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit
import SVProgressHUD
let weiboAPPKey = "2476814577"//"2707543009"
let weiboRedirect_Uri = "http://www.itheima.com"//"http://www.itcast.cn"
let weiboClient_secret = "10f3cb763ad07697322f12e7e045b68b"//"975492f53ff3df657f0c435e935ef822"
class HMOAuthViewController: UIViewController , UIWebViewDelegate{


    private lazy var webView: UIWebView = UIWebView()
    override func loadView() {
        
        webView.isOpaque = false// 解决底部webView黑条,改成透明解决黑条问题
        webView.delegate = self
        view = webView
    }
    
    private func RequestLogin() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(weiboAPPKey)&redirect_uri=\(weiboRedirect_Uri)"
        let request = URLRequest(url: URL(string: urlString)!)
        webView.loadRequest(request)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        RequestLogin()
        
        setupNavUI()
    }
    
    private func setupNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
        navigationItem.title = "微博"
        
    }
    
    @objc private func cancelAction() {
        
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        
//        print(#function)
//        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123'")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '328272127@qq.com';document.getElementById('passwd').value = 'ZHxr1111'")
    }
    
//    uiwebviewdelegate
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        guard let url = request.url else { return false }
//        print(url.absoluteString)
        if !url.absoluteString.hasPrefix(weiboRedirect_Uri) {
            return true
        }
        if let query = url.query , query.hasPrefix("code="){
            let code = query.substring(from: "code=".endIndex)
//            requestAccesstoken(code: code)
            HMUserAccountViewModel.sharedUserAccountViewModel.requestAccesstoken(code: code, callBack: { (isSuccess) in
                if isSuccess {
                    print("login success")
                    self.dismiss(animated: false, completion: { 
                        
                        NotificationCenter.default.post(name: Notification.Name(switchRootViewController), object: self)
                    })
                }
            })
        } else {
            //取消授权
            self.dismiss(animated: true, completion: nil)
        }
//        print(url.query)
        return false
    }
    
    
    func webViewDidStartLoad(_ webView: UIWebView)
    {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error)
    {
        SVProgressHUD.dismiss()
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}
